package com.jyun;

import java.sql.*;

public class ConnectDataBase {
    private String url;
    private String name;
    private String psw;
    private Statement statement=null;
    public ConnectDataBase(String url,String name,String psw){
        this.url=url;
        this.name=name;
        this.psw=psw;
        connectDataBase();
    }

    //连接数据库
    private void connectDataBase(){
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection connection= DriverManager.getConnection(url,name,psw);
            System.out.println("数据库连接成功！");
            statement=connection.createStatement();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //查询数据
    public String select(String table,String userName){
        try {
            ResultSet resultSet=statement.executeQuery("select pwd from "+table+" where userName='"+userName+"'");
//            String s = resultSet.getString("pwd");
//            return s;
            try {
                while(resultSet.next()){
                    try {
                            String s = resultSet.getString(1);
                            return s;

                    }catch(Exception e){}
                }
            } catch (SQLException e) {
//            e.printStackTrace();
            }
            System.out.println("查找的信息不存在");
            return "0";
        } catch (SQLException e) {
            System.out.println("查找的信息不存在");
//            e.printStackTrace();
            return "0";
        }
    }


    //删除数据
    public int delete(String table,String userName){
        try {
            int i=statement.executeUpdate("delete from "+table+" where userName='"+userName+"'");
            return i;
        } catch (SQLException e) {
            System.out.println("删除的信息不存在");
//            e.printStackTrace();
            return 0;
        }
    }

    //修改数据
    public int update(String table,String userName,String newName,String newPwd){
        try {
            int i=statement.executeUpdate("update "+table+" set userName='"+newName+"' , pwd='"+newPwd+"' where userName='"+userName+"'");
            return i;
        } catch (SQLException e) {
            System.out.println("需要修改的信息不存在");
//            e.printStackTrace();
            return 0;
        }
    }

    //插入数据
    public int insert(String table,String userName,String pwd){
        try {
            int i=statement.executeUpdate("insert into "+table+" (userName,pwd) values ('"+userName+"','"+pwd+"')");
            return i;
        } catch (SQLException e) {
            System.out.println("用户名已存在");
//            e.printStackTrace();
            return 0;
        }
    }
}
